package com.tarena.lbs.basic.web.fitlers;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.basic.web.thread.AuthenticationUtil;
import com.tarena.lbs.basic.web.thread.CustomThreadLocal;
import com.tarena.lbs.common.passport.encoder.JwtEncoder;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 在springboot的web应用使用生效一个过滤器
 * 1. 创建一个过滤器 成为容器bean对象
 * 2. 必须实现过滤器的接口Filter 或者继承接口下的一些抽象类
 */
@Component
//@Order(100)
@Slf4j
public class AuthenticationFilter implements Filter {
    @Autowired
    private JwtEncoder<UserPrinciple> jwtEncoder;

    //private CustomThreadLocal<UserPrinciple> customThreadLocal;
    /**
     * 完全当前服务进程 全局统一过滤入口的认证解析
     * @param servletRequest 满足servlet标准的请求 当前100%确定是http请求
     * @param servletResponse 满足servlet标准的响应 当前100%确定是http响应
     * @param filterChain 将过滤器对象 嵌入连接整条流程的过滤连对象
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("过滤器开始执行 认证解析jwt的过程");
        //1.判断请求是否是http请求
        if (servletRequest instanceof HttpServletRequest){
            //是http请求
            HttpServletRequest req = (HttpServletRequest) servletRequest;
            //2.获取请求头
            String jwt = req.getHeader("Authorization");
            //3.判断是否是空 不空
            if (jwt!=null&&jwt.length()>0){
                try{
                    UserPrinciple userPrinciple=
                            jwtEncoder.getLoginFromToken(jwt,UserPrinciple.class);
                    //customThreadLocal.save(userPrinciple);
                    AuthenticationUtil.save(userPrinciple);
                    log.info("解析jwt成功,拿到用户认证对象:{}",userPrinciple);
                }catch (BusinessException e){
                    log.error("解析jwt失败",e);
                }
            }
        }
        /*Thread thread = Thread.currentThread();
        log.info("过滤器执行完毕,当前线程:{}",thread);*/
        //调用过滤链对象 将请求和相应向后调用
        filterChain.doFilter(servletRequest,servletResponse);
        //在请求 响应即将返回的时候,将当前请求线程数据清空
        AuthenticationUtil.clear();
    }
}
